import 'package:objectbox/objectbox.dart';

import '../../../objectbox.g.dart';
import '../basemodel.dart';
import '../../config.dart';
import '../../network.dart';
import '../wallet_model/wallet_model.dart';

@Entity()
class WalletInfo {
  @Id()
  int id;
  int walletId;
  int createTime;
  String privateKey;
  String chainShortName;
  String address;
  String? balance;

  WalletInfo(
      {this.id = 0,
      required this.walletId,
      required this.createTime,
      required this.privateKey,
      required this.chainShortName,
      required this.address,
      this.balance});

  Chain? getChain() {
    for (var c in ChainList().chains) {
      if (c.shortName == chainShortName) {
        return c;
      }
    }
    return null;
  }

  bool isCustomChain() {
    return chainShortName.startsWith(Config.customChainShortNamePrefix);
  }

  @override
  String toString() {
    return '{id: $id, walletId: $walletId, createTime: $createTime, privateKey: $privateKey, chainShortName: $chainShortName, address: $address, balance: $balance}';
  }
}

class WalletInfoModel extends BaseModel<WalletInfo> {
  WalletInfoModel(Box<WalletInfo> box) : super(box);

  updateChainShortName(String oldChainShortName, String newChainShortName) {
    List<WalletInfo> list = box.query(WalletInfo_.chainShortName.equals(oldChainShortName)).build().find();
    for (var w in list) {
      w.chainShortName = newChainShortName;
    }

    box.putMany(list, mode: PutMode.update);
  }

  updateWalletBalance(WalletInfo listItem) {
    box.put(listItem, mode: PutMode.update);
  }


  // 获取 当前 钱包 id
  WalletInfo? getWalletInfoById(int id) {
    return box.query(WalletInfo_.id.equals(id)).build().findFirst();
  }

  WalletInfo? getFirstWalletInfo(Wallet wallet) {
    return box.query(WalletInfo_.walletId.equals(wallet.id)).build().findFirst();
  }

  WalletInfo? getWalletInfoByWalletIdAndChain(int walletId, String chainShortName) {
    return box
        .query(WalletInfo_.walletId.equals(walletId) & WalletInfo_.chainShortName.equals(chainShortName))
        .build()
        .findFirst();
  }

  List<WalletInfo> getWalletInfoListByWalletId(int walletId) {
    return box.query(WalletInfo_.walletId.equals(walletId)).build().find();
  }

  List<WalletInfo> getAllWallet() {
    return box.query().build().find();
  }
}
